package com.controller;

import com.Security.encodeUtil;
import com.auth.checkCode;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");
        HttpSession session = req.getSession(true);
        BufferedImage img = checkCode.getImage(checkCode.getWidth(), checkCode.getHeight(), checkCode.getImageType());

        Graphics graphics =checkCode. getGraphics(img);



        String code = checkCode.getCheckCode(checkCode.getChars()); //因为这里的checkCode是大写的所以在用户输入需要转换

        session.removeAttribute("code"); //先remove

        session.setAttribute("code", encodeUtil.encode(code.toUpperCase())); //encode之后放入session


        checkCode. setFontColor(graphics);

        checkCode.  drawString(code,graphics);

        checkCode.  drawLine(graphics);

        checkCode.makeDir(checkCode.getDirPath());

        //resp.getOutputStream() 用响应的流进行输出
        checkCode. outputImage(img,checkCode.getFormat(),resp.getOutputStream());

        graphics.dispose();

        img.flush();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
